package org.giovanolli.mumi.controller.report;

import org.giovanolli.mumi.controller.AbstractController;
import org.giovanolli.mumi.controller.AbstractModel;
import org.giovanolli.mumi.entities.Movement;
import org.giovanolli.mumi.entities.MovementType;
import org.giovanolli.mumi.entities.filter.MovementFilter;
import org.giovanolli.mumi.entities.filter.PatientFilter;
import org.giovanolli.mumi.service.MovementService;
import org.giovanolli.mumi.service.PatientService;
import org.giovanolli.mumi.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller("movementController")
public class MovementController extends AbstractController<Movement> {

	@Autowired
	private MovementService service;

	@Autowired
	private PatientService patientService;

	@Autowired
	private MovementModel model;

	@Override
	protected void bindEntityToModel() {
		Movement editedMovement = model.getEditedEntity();
	}

	@Override
	protected void bindModelToEntity() {
		Movement editedMovement = model.getEditedEntity();
	}

	public Double calculateTotal() {
		Double rv = 0d;
		int factor = 1;
		for (Movement movement : model.getList()) {
			if (movement.getMovementType().equals(MovementType.NEGATIVE)) {
				factor = -1;
			} else {
				factor = 1;
			}
			rv += (factor * movement.getFee());
		}
		return rv;
	}

	protected Class<Movement> getEntityClass() {
		return Movement.class;
	}

	@Override
	protected AbstractModel<Movement> getModel() {
		return model;

	}

	@Override
	protected Service<Movement> getService() {
		return service;
	}

	public void init() {
		super.init();
		model.setFilter(new MovementFilter());
		populateNonEntityPropertiesToModel();
	}

	@Override
	public void populateNonEntityPropertiesToModel() {
		model.setSelectablePatients(patientService.getList(new PatientFilter()));
	}

	@Override
	public void search() {
		super.search();
		model.setTotalAmount(calculateTotal());
	}
}
